import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_status.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:vischat/core/utils/custom_date_utils.dart';
import 'package:vischat/generated/icons/app_icons.dart';
import 'package:vischat/modules/home/socialize/chat/widgets/message_bubble.dart';
import 'package:vischat/modules/home/socialize/chat/widgets/message_item/message_item_controller.dart';
import 'package:vischat/shared/widgets/avatar.dart';

class MessageItem extends GetView<MessageItemController> {
  final int index;
  const MessageItem(this.index, {super.key});

  @override
  Widget build(BuildContext context) {
    final V2TimMessage message = controller.chatController.messages[index];
    final isMe = message.sender != controller.chatController.conversation.userID;

    return Column(
      crossAxisAlignment:
          isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
      children: [
        if (_shouldShowTime(index))
          Container(
            padding: EdgeInsets.symmetric(vertical: 10.h),
            alignment: Alignment.center,
            child: Text(
              CustomDateUtils.formatTimestamp(
                message.timestamp!,
                withTime: true,
              ),
              style: TextStyle(color: Colors.grey, fontSize: 24.sp),
            ),
          ),
        Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.80,
          ),
          child:
              isMe
                  ? Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Flexible(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            message.status ==
                                    MessageStatus.V2TIM_MSG_STATUS_SENDING
                                ? SizedBox(
                                  width: 18.w,
                                  height: 18.w,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2.w,
                                  ),
                                )
                                : message.status ==
                                    MessageStatus.V2TIM_MSG_STATUS_SEND_FAIL
                                ? GestureDetector(
                                  onTap: () => controller.sendController.resend(message),
                                  child: Icon(
                                    AppIcons.fail,
                                    size: 36.r,
                                    color: Colors.red,
                                  ),
                                )
                                : SizedBox(),
                            SizedBox(width: 10.w),
                            Flexible(
                              child: _buildMessageContent(message, isMe),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(width: 10.w),
                      AppAvatar(
                        avatar: message.faceUrl ?? '',
                        size1: 34.r,
                        size2: 34.r,
                      ),
                    ],
                  )
                  : Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      AppAvatar(
                        avatar: message.faceUrl ?? '',
                        size1: 34.r,
                        size2: 34.r,
                      ),
                      SizedBox(width: 10.w),
                      Flexible(child: _buildMessageContent(message, isMe)),
                    ],
                  ),
        ),
      ],
    );
  }

  Widget _buildMessageContent(V2TimMessage message, bool isMe) {
    switch (message.elemType) {
      case MessageElemType.V2TIM_ELEM_TYPE_TEXT:
        return TextMessageBubble(
          text: message.textElem?.text ?? '',
          isMe: isMe,
          status: message.status ?? 1,
        );
      case MessageElemType.V2TIM_ELEM_TYPE_IMAGE:
        return ImageMessageBubble(
          url: message.imageElem?.imageList?.first?.url ?? '',
          isMe: isMe,
        );
      // 其他消息类型处理...
      default:
        return Text('[${'messageType.notSupported'.tr}]');
    }
  }

  bool _shouldShowTime(int index) {
    if (index < 0 || index >= controller.chatController.messages.length) return false;
    if (index == 0) return false;
    final current = controller.chatController.messages[index].timestamp ?? 0;
    final previous = controller.chatController.messages[index - 1].timestamp ?? 0;
    if (current == 0 || previous == 0) return false;
    return previous - current > 10 * 60; // 10分钟间隔
  }
}
